package map.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.navi.BaiduMapNavigation
import com.baidu.mapapi.navi.NaviParaOption
import com.baidu.mapapi.search.route.WalkingRouteLine
import com.baidu.mapapi.search.route.WalkingRouteResult
import com.zjw.zy.ext.logE
import com.zjw.zy.ext.shortToast
import com.zjw.zy.smi.JustWithIt
import com.zjw.zy.utils.AppUtils
import map.default.DefaultGetRoutePlanResultListener
import map.ext.locationManager
import map.ext.map
import map.ext.mapManager
import map.ext.routeManager
import java.lang.Exception

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/10/24 15:19
 * @description：
 */
class RoutePlanViewModel : MapBaseViewModel() {

    companion object {
        private const val TAG = "RouteViewModel"
    }

    /**
     * 路线规划结果
     * */
    private val routeWalkResult = MutableLiveData<List<WalkingRouteLine>>()
    fun getRouteWalkResult(): LiveData<List<WalkingRouteLine>> = routeWalkResult

    private var currentPath: WalkingRouteLine? = null

    private var mEnd: LatLng? = null

    fun walkPlan(end: LatLng, call: JustWithIt<Boolean>) {
        mEnd = end
        routeManager().walkPlan(end = end, call = object : DefaultGetRoutePlanResultListener {
            override fun onGetWalkingRouteResult(p0: WalkingRouteResult?) {
                //路线
                val routeResult = p0?.routeLines
                if (routeResult.isNullOrEmpty()) {
                    "fail route plan".logE(TAG)
                    call.onWith(false)
                } else {
                    routeResult.let {
                        routeWalkResult.postValue(it)
                    }
                    call.onWith(true)
                }
            }
        })
    }

    fun openMapNavi() {
        NaviParaOption().startPoint(locationManager().locationLatLng())
            .endPoint(mEnd).apply {
                try {
                    BaiduMapNavigation.openBaiduMapWalkNavi(this, AppUtils.getMapActivity()).let {
                        if (!it){
                            "还未安装百度地图".shortToast()
                        }
                    }
                } catch (e: Exception) {
                    "导航失败".shortToast()
                }
            }
    }

    fun drawPath(routeLine: WalkingRouteLine) {
        currentPath = routeLine
        mapManager().walkRouteOverlay().apply {
            map().clear()
            this.setData(routeLine)
            this.addToMap()
            this.zoomToSpan()
            mapManager().zoomOut()
        }
    }
}